<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id === 0 ? '新增地址' : '编辑地址'"
      width="1100"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 400px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="标题:" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="分类:" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择">
              <el-option v-for="item in playTypeData" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="老人:" prop="elderly">
            <el-button v-if="elderlyData.length === 0" type="primary" @click="handleSelect">
              选择老人
            </el-button>
            <span v-else @click="handleSelect">{{ elderlyData.join(",") }}</span>
          </el-form-item>
          <el-form-item label="精神未结内容:">
            <MyEditor v-model="ruleForm.content" />
          </el-form-item>
          <el-form-item label="上传图片:" prop="pictures">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :action="BaseImgUrl"
              :headers="headers"
              :on-change="handleChange"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择老人 -->
    <elderlyDialog
      v-if="selectDialogVisible"
      :elderlys="elderlys"
      @selectClose="handelSelectClose"
      @selectElderly="handelSelectElderly"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import MyEditor from "@/components/care/Editor/editorView.vue";
import { addPlayParams } from "@/api/care/activity/type";
import type { UploadProps, UploadUserFile } from "element-plus";
import { getToken } from "@/utils/auth";
import elderlyDialog from "./elderly.vue";
import { playAdd, playGet, playType, playUpdate } from "@/api/care/activity/activity";

// 图片根路径
const BaseImgUrl = import.meta.env.VITE_APP_API_URL + "/api/upload/add";
const headers = { Authorization: getToken() };

const props = defineProps({ listParams: Number });
let id = props.listParams as number;

const dialogVisible = ref(true);

const ruleForm = reactive<addPlayParams>({
  id: 0,
  title: "",
  type: undefined,
  content: "",
  elderly: [],
  pictures: [],
});

// 获取单条数据
const getData = async () => {
  let res = await playGet(id);
  // console.log(res);
  elderlyData.value = res.elderly.map((item) => item.elderlyName);
  fileList.value = res.pictures.map((item) => ({ name: item.picture }));
  Object.assign(ruleForm, res);
};

// 选择老人
const selectDialogVisible = ref(false);
const handleSelect = () => {
  selectDialogVisible.value = true;
};
const elderlyData = ref<string[]>([]); //选中返回的数据
let elderlys = ref<any[]>([]); // 重新赋值
const handelSelectElderly = (val: any[]) => {
  ruleForm.elderly = val.map((item) => ({ elderlyId: item.id }));
  elderlyData.value = [];
  let arr = Array.from(new Set(val.map((item) => item.id))).map((id) =>
    val.find((item) => item.id === id)
  );
  elderlys.value = arr;

  arr.map((item) => {
    elderlyData.value.push(item.name);
  });
};

// 获取活动列表
const playTypeData = ref<any[]>([]);
const getPlayType = async () => {
  let res = await playType();
  playTypeData.value = res.list;
};

// 添加
const submitForm = async () => {
  await playAdd(ruleForm);
  ElMessage.success("添加成功");
  emit("close");
};

// 修改
const update = async () => {
  await playUpdate(ruleForm);
  ElMessage.success("修改成功");
  emit("close");
};

const submit = () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      ruleForm.id === 0 ? await submitForm() : await update();
    }
  });
};

// 上传图片
const fileList = ref<any[]>([]);
const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  const transformedPictures = uploadFiles.map((file) => ({
    picture: file.url || file.name,
  }));
  ruleForm.pictures = transformedPictures;
  fileList.value = uploadFiles;
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<addPlayParams>>({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  type: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  elderly: [{ required: true, message: "请选择老人", trigger: "change" }],
});

const emit = defineEmits(["close"]);
const handleClose = () => {
  emit("close");
};

// 关闭弹框
const handelSelectClose = () => {
  selectDialogVisible.value = false;
};

onMounted(() => {
  getPlayType();
  getData();
});
</script>

<style scoped lang="less"></style>
